/**
 * 用户列表
 */
package com.xiaomuwu.android.ui.shared

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.xiaomuwu.android.MainActivity
import com.xiaomuwu.android.R
import com.xiaomuwu.android.XiaoMuWuApplication
import com.xiaomuwu.android.logic.model.ForReleRes
import com.xiaomuwu.android.logic.model.ForReleUser
import com.xiaomuwu.android.logic.model.ForUser
import com.xiaomuwu.android.ui.Displayer
import com.xiaomuwu.android.ui.ForSearch
import com.xiaomuwu.android.ui.home.UserViewModel
import com.xiaomuwu.android.ui.LoginStatus
import com.xiaomuwu.android.ui.detail.UserDetailFragment
import com.xiaomuwu.android.ui.rele.ReleUserViewModel
import kotlinx.android.synthetic.main.res_list_fragment.*
import kotlinx.android.synthetic.main.user_list_fragment.*

class UserListFragment:Fragment() {

    private val userViewModel by lazy { ViewModelProviders.of(this).get(
        UserViewModel::class.java)}

    private val releUserViewModel by lazy{ ViewModelProviders.of(this).get(
        ReleUserViewModel::class.java)}

    private lateinit var adapter : UserListAdapter

    private lateinit var updateUserReceiver: UpdateUserReceiver // 刷新用户列表广播接收器
    private lateinit var updateReleUserReceiver: UpdateReleUserReceiver // 刷新相关用户列表广播接收器
    private lateinit var showUserDetailReceiver: ShowUserDetailReceiver  // 显示用户详情广播接收器

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.user_list_fragment,container,false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        // 设置广播过滤器并注册广播接收器
        updateUserReceiver=UpdateUserReceiver()
        val updateUserFilter=IntentFilter()
        updateUserFilter.addAction("com.xiaomuwu.android.UpdateUser")
        XiaoMuWuApplication.context.registerReceiver(updateUserReceiver,updateUserFilter)

        updateReleUserReceiver=UpdateReleUserReceiver()
        val updateReleUserFilter=IntentFilter()
        updateReleUserFilter.addAction("com.xiaomuwu.android.UpdateReleUser")
        XiaoMuWuApplication.context.registerReceiver(updateReleUserReceiver,updateReleUserFilter)

        showUserDetailReceiver = ShowUserDetailReceiver()
        val showUserDetailFilter = IntentFilter()
        showUserDetailFilter.addAction("com.xiaomuwu.android.ShowUserDetail")
        XiaoMuWuApplication.context.registerReceiver(showUserDetailReceiver,showUserDetailFilter)

        val layoutManager= LinearLayoutManager(activity)
        userListRecyclerView?.layoutManager=layoutManager

        // 根据页面设置用户查询监听
        if(Displayer.pageStatus == "Home") {
            adapter= UserListAdapter(userViewModel.userList)
            userListRecyclerView?.adapter=adapter
            userViewModel.userLiveData.observe(viewLifecycleOwner, { result->
                val user=result.getOrNull()
                if(user!=null){
                    userViewModel.userList.clear()
                    userViewModel.userList.addAll(user)
                    adapter.notifyDataSetChanged()
                    Log.d("UserListFragment","User查询成功")
                }else{
                    Log.d("UserListFragment","User查询失败")
                }
                scrollToBrowse()    // 滚动到浏览位置
            })

            // 刷新用户列表
            userViewModel.getUserLiveData(ForUser(ForSearch.contentName, ForSearch.userSortBy))
            //check(与上面一段的顺序是否影响运行)
        }else if(Displayer.pageStatus =="Follow" || Displayer.pageStatus =="Fans") {
            adapter= UserListAdapter(releUserViewModel.releUserList)
            userListRecyclerView?.adapter=adapter
            releUserViewModel.releUserLiveData.observe(viewLifecycleOwner, { result->
                val user=result.getOrNull()
                if(user!=null){
                    releUserViewModel.releUserList.clear()
                    releUserViewModel.releUserList.addAll(user)
                    adapter.notifyDataSetChanged()
                    Log.d("UserListFragment","ReleUser查询成功")
                }else{
                    Log.d("UserListFragment","ReleUser查询失败")
                }
                scrollToBrowse()    // 滚动到浏览位置
            })
            releUserViewModel.getReleUserLiveData(ForReleUser(LoginStatus.user_ID!!,
                ForSearch.contentName)) // 刷新相关用户列表
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        // 取消注册广播接收器
        XiaoMuWuApplication.context.unregisterReceiver(updateUserReceiver)
        XiaoMuWuApplication.context.unregisterReceiver(updateReleUserReceiver)
        XiaoMuWuApplication.context.unregisterReceiver(showUserDetailReceiver)
    }

    /**
     * 滚动到浏览位置函数
     */
    private fun scrollToBrowse() {
        // 定位浏览位置
        val range=0 until userViewModel.userList.size
        if(Displayer.userPosition!=0){
            for(position in range){
                if(userViewModel.userList[position].id==ForSearch.userID){
                    Displayer.userPosition=position
                }
            }
        }

        try {
            userListRecyclerView?.scrollToPosition(Displayer.userPosition)
            Displayer.userPosition=0    // 重置浏览位置
            Log.d("UserListFragment","滚动成功")
        }catch (e:Exception){
            e.printStackTrace()
            Log.d("UserListFragment","滚动失败")
        }
    }

    /**
     * 刷新用户列表广播接收器
     */
    inner class UpdateUserReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            userViewModel.getUserLiveData(ForUser(ForSearch.contentName, ForSearch.userSortBy))
        }
    }

    /**
     * 刷新相关用户列表广播接收器
     */
    inner class UpdateReleUserReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            releUserViewModel.getReleUserLiveData(ForReleUser(LoginStatus.user_ID!!,ForSearch.contentName))
        }
    }

    /**
     * 显示用户详情广播接收器
     */
    inner class ShowUserDetailReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            // 切换至用户详情页
            if (activity != null) {
                val mainActivity = activity as MainActivity
                mainActivity.hideKeyboard() // 收起键盘
                mainActivity.replaceFragment(UserDetailFragment())
            }
        }
    }

}